package com.reeygu.base.entity;

import java.util.concurrent.locks.ReentrantLock;

public class LSaleTicket {
    private int number = 30;
    //创建可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    //操作方法，卖票（通过字段 synchronized 进行加锁）
    public synchronized void saleA() {
        //上锁
        lock.lock();
        //如果这里出异常，那锁将无法释放
        if(number > 0) {
            System.out.println(Thread.currentThread().getName() + " 卖出1张票，剩余:" + (number--));
        }
        lock.unlock();
    }
    //优化
    public synchronized void saleB() {
        //上锁
        lock.lock();
        try {
            //如果这里出异常，也可以释放锁
            if(number > 0) {
                System.out.println(Thread.currentThread().getName() + " 卖出1张票，剩余:" + (number--));
            }
        } finally {
            lock.unlock();
        }
    }
}
